from cmdNopass import *
import vm

def createVm(logger):
    logger.info('creating vm ...')
    master = vm.createMaster()
    slave = vm.createSlave()
    logger.info('creating vm succeed!')
    return (master, slave)

def startVm(master, slave, logger):
    logger.info('starting vm ...')
    while True:
        sts, ret= cmd('ping -c 1 -w 1 %s' % master)
        if not sts:
            break
    while True:
        sts, ret= cmd('ping -c 1 -w 1 %s' % slave)
        if not sts:
            break
    logger.info('starting vm succeed!')



def createUser(host, username, password, logger):
    logger.info('creating user ...')
    cmd = '"useradd -d /var/www/html/ '+username+' && echo '+password+' | passwd --stdin '+username+'"'
    sts, ret = sshCmd(host,'root',cmd)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('creating user failed!')
        return 1
    else:
        logger.info('creating user succeed!')
        return 0

def nfsConf(master, slave, logger):
    logger.info('configuring nfs ...')
    cmd('echo "/var/www/html '+slave+'(rw)" > ../temp/exports')
    src = '../temp/exports'
    dest = '/etc/'
    sts, ret = scpCmd(master, src, dest)
    os.remove(src)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('configuring nfs failed!')
        return 1
    else:
        logger.info('configuring nfs succeed!')
        return 0

def nfsExport(master, logger):
    logger.info('nfs exportfs ...')
    cmd = 'exportfs -arv'
    sts, ret = sshCmd(master, 'root', cmd)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('nfs exportfs failed!')
        return 1
    else:
        logger.info('nfs exportfs succeed!')
        return 0

def mountSlave(slave, master, logger):
    logger.info('mounting nfs on slave ...')
    cmd = 'mount -t nfs -o bg '+master+':/var/www/html /var/www/html'
    sts, ret = sshCmd(slave, 'root', cmd)
    logger.debug(ret.strip())
    if ret.strip().endswith("already mounted or busy"):
        logger.info('mounting nfs on slave succeed!')
        return 0
    elif sts:
        logger.error('mounting nfs on slave failed!')
        return 1
    else:
        logger.info('mounting nfs on slave succeed!')
        return 0

def fstabConf(slave, master, logger):
    import os,shutil

    logger.info('configuring fstab ...')
    shutil.copy('../templateconfig/fstab.template','../temp/fstab')
    cmd('echo "'+master+':/var/www/html   /var/www/html   nfs rw,bg   0   0" >> ../temp/fstab')
    src = '../temp/fstab'
    dest = '/etc/'
    sts, ret = scpCmd(slave,src,dest)
    os.remove(src)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('configuring fstab failed!')
        return 1
    else:
        logger.info('configuring fstab succeed!')
        return 0

def loadBalanceConf(master, slave, logger):
    import os,shutil

    logger.info('configuring load balance ...')
    shutil.copy('../templateconfig/haproxy.cfg.template','../temp/haproxy.cfg')
    cmd('echo "        server s1 '+slave+':8088 cookie appinst1 check" >> ../temp/haproxy.cfg')
    src = '../temp/haproxy.cfg'
    dest = '/usr/local/haproxy/'
    sts, ret = scpCmd(master,src,dest)
    os.remove(src)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('configuring load balance failed!')
        return 1
    else:
        logger.info('configuring load balance succeed!')
        return 0

def loadBalanceStart(master, logger):
    logger.info('starting load balance ...')
    cmd = 'haproxy -f /usr/local/haproxy/haproxy.cfg'
    sts, ret = sshCmd(master, 'root', cmd)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('starting load balance failed!')
        return 1
    else:
        logger.info('starting load balance succeed!')
        return 0

def phpmyadminConf(host, logger):
    import os,shutil

    logger.info('configuring phpmyadmin ...')
    shutil.copy('../templateconfig/config.inc.php.template','../temp/config.inc.php')
    cmd('sed -i "72c \$cfg[\'blowfish_secret\']=\''+host+'\';" ../temp/config.inc.php')
    cmd('sed -i "95c \$cfg[\'Servers\'][\$i][\'host\']=\''+host+'\';" ../temp/config.inc.php')
    src = '../temp/config.inc.php'
    dest = '/var/www/html/craneutility/phpmyadmin/'
    sts, ret = scpCmd(host,src,dest)
    os.remove(src)
    logger.debug(ret.strip())
    if ret.startswith("ssh:"):
        logger.error('configuring phpmyadmin failed!')
        return 1
    else:
        logger.info('configuring phpmyadmin succeed!')
        return 0

def mysqlAddUser(host, username, password, scope, logger):
    import MySQLdb

    logger.info('adding mysql user ...')
    try:
        conn=MySQLdb.connect(host=host, user='root', passwd='crane')
    except:
        logger.debug('mysql server %s can\'t be connected!' %(host))
        logger.error('adding mysql user failed!')
        return 1

    cursor=conn.cursor()
    if not scope:
        cursor.execute("grant all privileges on *.* to %s@localhost identified by '%s'" % (username,password))
    else:
        cursor.execute("grant all privileges on *.* to "+username+"@'%'"+" identified by '"+password+"'")
    cursor.close()
    conn.close()
    logger.info('adding mysql user succeed!')
    return 1

